/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.test;

import cn.ac.iie.di.ban.news.server.check.CheckDesc;
import cn.ac.iie.di.ban.news.server.check.CheckResult;
import cn.ac.iie.di.ban.news.server.check.JsonChecker;
import cn.ac.iie.di.ban.news.server.runtime.RuntimeEnv;
import cn.ac.iie.di.ban.news.server.runtime.RuntimeEnvException;
import cn.ac.iie.di.ban.news.server.util.HttpUtils;
import cn.ac.iie.di.ban.news.server.util.HttpUtils.Result;
import static cn.ac.iie.di.ban.news.server.util.HttpUtils.httpPost;
import cn.ac.iie.di.datadock.rdata.exchange.client.core.REFieldType;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author Austin
 */
public class test {

    private static Logger logger = Logger.getLogger(test.class);
    private ArrayBlockingQueue<String> configHosts;
    private long configInteval;
    private boolean needHttps;

    public test(int updateIntervalSecond, boolean needHttps) {
        this.configInteval = updateIntervalSecond;
        this.needHttps = needHttps;
    }

    public static void main(String[] args) throws Exception {
        String[] cmds = {"curl", "-i", "-XPOST", "\"http://192.168.11.94:8086/write?db=zzjr_data_monitor\" --data-binary \"FormalErrorTable,formal_key=qqqqq,error_type=6-6,data_type=6  value=\\\"s  addfgzxasd\\\"\""};
        ProcessBuilder pb = new ProcessBuilder(cmds);
        pb.redirectErrorStream(true); 
        Process p;
        try {
            p = pb.start();
            BufferedReader br = null;
            String line = null;
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = br.readLine()) != null) {
                System.out.println("\t" + line);
            }
            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

//        HashMap<String, String> map = new HashMap<>();
//        map.put("--data-binary", "FormalErrorTable,formal_key=qqqqq,error_type=6-6,data_type=6 value=asddfg");
//        http://192.168.11.94:8086/write?db=zzjr_data_monitor
//        map.put("db", "zzjr_data_monitor");
//        Result x = HttpUtils.httpPost("http://192.168.11.94:8086/write?db=zzjr_data_monitor", map);
//        System.out.println(x.content);
//        System.out.println(x.statusCode);
//        System.out.println(x.reasonPhrase);
//        JSONObject obj = JSONObject.parseObject("{\n" +
//"	\"key\": \"25e600657ebacc25fc54076c682d2c48\",\n" +
//"	\"msg_type\": \"1\",\n" +
//"	\"msg_version\": \"v1.0\",\n" +
//"	\"record_list\": [{\n" +
//"		\"AUTHOR\": \"5paw5rWq5aix5LmQ\",\n" +
//"		\"CHANNEL\": \"1\",\n" +
//"		\"COLUMN\": [\"APP/娱乐栏目\"],\n" +
//"		\"DOMAIN\": \"t.m.youth.cn\",\n" +
//"		\"ORIGINURL\": \"aHR0cDovL3QubS55b3V0aC5jbi90cmFuc2Zlci90b3V0aWFvL3VybC9mdW4ueW91dGguY24vZ256eC8yMDE4MDIvdDIwMTgwMjIyXzExNDMwMzExLmh0bQ==\",\n" +
//"		\"PHOTOURLS\": [\"aHR0cDovL2kucHN0YXRwLmNvbS9sYXJnZS82NWNhMDAwMTY2OGRlOTJlOWM3Zg==,aHR0cDovL2kucHN0YXRwLmNvbS9sYXJnZS82MDA3MDAwZDAwMTU3ZTAyODIzYQ==,aHR0cDovL2kucHN0YXRwLmNvbS9sYXJnZS82MDA4MDAwNmI0M2JlYWJiNjU2Yw==,aHR0cDovL2kucHN0YXRwLmNvbS9sYXJnZS82MDAzMDAwNzA5MTRmNDQxZjI3OA==\"],\n" +
//"		\"PUBLISHTIME\": \"20180222075800\",\n" +
//"		\"SOURCE\": [\"youth.cn\"],\n" +
//"		\"STATE\": \"1\",\n" +
//"		\"TEXT\": \"PGltZyBzc193aWR0aD0iNjkwIiBzc19oZWlnaHQ9IjU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9wPjxpbWcgc3Nfd2lkdGg9IjY5MCIgc3NfaGVpZ2h0PSI1MTgiIHNzX3dlYl91cmk9IiIgc3NfdXJpPSI2MDA4MDAwNmI0M2JlYWJiNjU2YyIgc3JjPSJodHRwOi8vaS5wc3RhdHAuY29tL2xhcmdlLzYwMDgwMDA2YjQzYmVhYmI2NTZjIiAgIG5lYXJfZHVwX2lkPSIxMTY4NTA3MTIzNzczMjcyOTQ2NyIgb2NyX3RleHQ9IiIgbWltZXR5cGU9ImltYWdlL2pwZWciPjxwPmJhYnnlkozlpojlpojnibXmiYvotbA8L3A+PGltZyBzc193aWR0aD0iNjkwIiBzc19oZWlnaHQ9IjUxOCIgc3Nfd2ViX3VyaT0iIiBzc191cmk9IjYwMDMwMDA3MDkxNGY0NDFmMjc4IiBzcmM9Imh0dHA6Ly9pLnBzdGF0cC5jb20vbGFyZ2UvNjAwMzAwMDcwOTE0ZjQ0MWYyNzgiICAgbmVhcl9kdXBfaWQ9IjE3MTAxNDg3ODkzMTMwNTA2ODA2IiBvY3JfdGV4dD0iIiBtaW1ldHlwZT0iaW1hZ2UvanBlZyI+PHA+6buE5pmT5piO5ZKM5aaI5aaIPC9wPg==\",\n" +
//"		\"TITLE\": \"YmFieem7hOaZk+aYjuWSjOWmiOWmiOmbquWcsOeJteaJi+i1sCBiYWJ557qi5ZSH5oqi55y86LaF576O\",\n" +
//"		\"UPLOADTIME\": \"20180222092431\"\n" +
//"	}],\n" +
//"	\"total_pushed_num\": \"1\"\n" +
//"}");
//        for (Object rec : obj.getJSONArray("record_list")) {
//            for (Map.Entry<String, Object> o : ((JSONObject) rec).entrySet()) {
//                String col = o.getKey();
//                Object v = o.getValue();
//                if ("PHOTOURLS".equals(col)) {
//                    String val = v.toString();
//                    JSONArray a = JSONArray.parseArray(val);
//                    String[] strs = new String[a.size()];
//                    for (int i = 0; i < a.size(); ++i) {
//                        strs[i] = a.getString(i);
//                    }
//                }
//            }
//        }
//            RuntimeEnv.init();
//            JsonChecker jc = new JsonChecker(Arrays.asList(RuntimeEnv.getParamAsStrings("data.config.host", new String[0])), 1000, false);
//            System.out.println("JC START");
//            jc.start();
//            System.out.println("JC START OVER");
//            CheckResult ru = jc.check("29dfc2bd6539f9d7f7c8d8cd037a82c3_2.0_appstore.info", JSONObject.parseObject("{\"5\":\"20180126143600\",\"6\":\"\",\"7\":\"20180126143600\",\"8\":\"20180126143600\",\"9\":\"20180126143600\"}"));
//            logger.info(ru.reason);
//            logger.info(ru.correct);
    }

//    public void run() {
//        
//        try {
//            Map<String, Set<JSONObject>> check = new HashMap<>();
//            JSONObject[] company = SearchTable("company_group", new JSONObject().toString());
//            for (JSONObject cpObj : company) {
//                JSONObject[] group = SearchTable("group_channel", "{\"g_id\":\"" + cpObj.getString("g_id") + "\"}");
//                for (JSONObject gObj : group) {
//                    JSONObject[] channel = SearchTable("channel", "{\"ch_id\":\"" + gObj.getString("ch_id") + "\"}");
//                    JSONObject[] channel_field = SearchTable("channel_field", "{\"ch_id\":\"" + gObj.getString("ch_id") + "\"}");
//                    Set<JSONObject> fileds = new HashSet<JSONObject>();
//                    for (JSONObject cfObj : channel_field) {
//                        JSONObject[] field = SearchTable("field", "{\"f_id\":\"" + cfObj.getString("f_id") + "\"}");
////                        System.out.println(Arrays.asList(field).size());
//                        fileds.add(field[0]);
//                    }
//                    check.put(cpObj.getString("formal_key") + "_" + cpObj.getString("version") + "_" + channel[0].getString("data_type"), fileds);
//                }
//            }
//            JsonChecker jsonChecker = new JsonChecker();
//            System.out.println(check);
//            String name = "";
//            for (String checkKeyName : check.keySet()) {
//                if (checkKeyName.equals("29dfc2bd6539f9d7f7c8d8cd037a82c3_2.0_appstore.info")) {
//                    System.out.println(checkKeyName);
//                }
//                Set<String> required = new HashSet<>();
//                Set<JSONObject> jsons = check.get(checkKeyName);
//                Map<String, String> srcMap = new HashMap<>();
//                Map<String, String> checkMap = new HashMap<>();
//                for (JSONObject j : jsons) {
//                    if ("yes".equalsIgnoreCase(j.getString("nullable"))) {
//                        required.add(j.getString("name"));
//                    }
//                    srcMap.put(j.getString("name"), j.getString("type"));
//                    checkMap.put(j.getString("name"), j.getString("format_check"));
//                }
//                jsonChecker.reg(checkKeyName, checkKeyName.split("_")[1],
//                        checkKeyName.split("_")[2],
//                        required,
//                        getParamAsCheckDescMap(checkMap),
//                        getParamAsTypeMap(srcMap));
//            }
//            CheckResult ru = jsonChecker.check("29dfc2bd6539f9d7f7c8d8cd037a82c3_2.0_appstore.info", JSONObject.parseObject("{\"5\":\"20180126143600\",\"6\":\"20600\",\"7\":\"20180126143600\",\"8\":\"20180126143600\",\"9\":\"20180126143600\"}"));
//            System.out.println(ru.reason);
//            System.out.println(ru.correct);
//            
//        } catch (Exception e) {
//            logger.error(e, e);
//        }
//    }
    /**
     * 表查询接口
     *
     * @param scope 表名
     * @param condition 查询where条件 json格式
     * @return 查询所得json数组
     * @throws Exception
     */
    public JSONObject[] SearchTable(String scope, String condition) throws Exception {
        JSONObject[] jsons = new JSONObject[0];
        HashMap<String, String> param = new HashMap<>();
        param.put("scope", scope);
        param.put("opration", "search");
        param.put("content", "{}");
        param.put("condition", condition);
        String host = "http://192.168.11.95:10250/data/";
//        configHosts.put(host);
        HttpUtils.Result result = httpPost(host, param);
        if (result.statusCode != HttpServletResponse.SC_OK) {
            logger.error("update " + host + " failed because :" + result.reasonPhrase);
        } else {
            JSONObject jsonObj = JSONObject.parseObject(result.content);
            if ("succeeded".equals(jsonObj.getString("status"))) {
                JSONArray array = jsonObj.getJSONArray("data");
                jsons = new JSONObject[array.size()];
                for (int i = 0; i < array.size(); i++) {
                    jsons[i] = array.getJSONObject(i);
                }
            }
        }
        return jsons;
    }

    public static Map<String, REFieldType> getParamAsTypeMap(Map<String, String> srcMap) throws RuntimeEnvException {
        HashMap<String, REFieldType> rtn = new HashMap<>();
        for (Map.Entry<String, String> entry : srcMap.entrySet()) {
            switch (entry.getValue().trim().toLowerCase()) {
                case "int":
                case "integer":
                case "n":
                case "i":
                case "\\d":
                case "int_s":
                    rtn.put(entry.getKey(), REFieldType.Int);
                    break;
                case "long":
                case "l":
                case "ld":
                case "long_s":
                    rtn.put(entry.getKey(), REFieldType.Long);
                    break;
                case "string":
                case "str":
                case "s":
                case "\\s":
                case "string_s":
                    rtn.put(entry.getKey(), REFieldType.String);
                    break;
                case "strings":
                case "string[]":
                case "array<string>":
                case "string_a":
                    rtn.put(entry.getKey(), REFieldType.Strings);
                    break;
            }
        }
        return rtn;
    }

    public static Map<String, CheckDesc[]> getParamAsCheckDescMap(Map<String, String> param) throws RuntimeEnvException {
        HashMap<String, CheckDesc[]> rtn = new HashMap<>();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            CheckDesc[] descs = new CheckDesc[entry.getValue().split("\\,").length];
            for (int i = 0; i < entry.getValue().split(",").length; i++) {
                CheckDesc desc = CheckDesc.parse(entry.getValue().split(",")[i]);
                descs[i] = desc;
            }
            if (descs.length != 0) {
                rtn.put(entry.getKey(), descs);
            }
        }
        return rtn;
    }
}
